package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.TreeNode;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.TreeSet;

public class LeetCodeTest0671 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2147483647);
        new LeetCodeTest0671().findSecondMinimumValue(root);
    }

    public int findSecondMinimumValue(TreeNode root) {
        Map<Integer, Integer> result = new HashMap<>();
        Stack<TreeNode> treeNodeStack = new Stack<>();
        treeNodeStack.push(root);
        while (!treeNodeStack.isEmpty()) {
            TreeNode node = treeNodeStack.pop();
            if (node.left != null && node.right != null) {
                treeNodeStack.push(node.right);
                treeNodeStack.push(node.left);
            } else {
                result.put(node.val, node.val);
            }
        }
        if (result.size() < 2) {
            return -1;
        }
        TreeSet<Integer> keySet = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer integer, Integer t1) {
                if (integer > t1) {
                    return 1;
                } else if (integer.equals(t1)) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        keySet.addAll(result.keySet());
        Object[] array = keySet.toArray();
        return (int) array[1];
    }
}
